package com.itheima.reggie.ctrl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.model.dto.DishDto;
import com.itheima.reggie.model.entity.Category;
import com.itheima.reggie.model.entity.Dish;
import com.itheima.reggie.model.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

// @reuseJava
/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info("接收到dishDto={}",dishDto.toString());

        dishService.savaWithFlavor(dishDto);

        //todo-优化 清理菜品缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
//        清理所有菜品的redis缓存数据
//        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(key);

        return R.success("新增菜品成功");
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("接收到dishDto={}",dishDto.toString());


        //更新也涉及到dish，dish_flavor两个表
        dishService.updateWithFlavor(dishDto);

        //todo-优化 清理菜品缓存
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
//        清理所有菜品的redis缓存数据
//        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(key);

        return R.success("修改菜品成功");
    }


    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize,String name){
        log.info("菜品信息分页查询，前端传来数据：page={},pagesize={},name={}",page,pageSize,name);

        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);//注意new Page<>(page,pageSize)中一定要加page,pageSize
        Page<DishDto> dishDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotBlank(name),Dish::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,queryWrapper);

        //对象拷贝，将pageInfo 拷贝到 dishDtoPage，在拷贝过程中忽略(不拷贝)records属性
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        //得到records
        List<Dish> records = pageInfo.getRecords();
        //处理records,并返回处理好的records
        List<DishDto> list = records.stream().map((record) -> { //item代表每个遍历出来的Dish对象
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);

            ////根据分类id找分类name
            //得到分类id
            Long categoryId = record.getCategoryId();
            //根据分类id得到分类name (分类id查询分类对象 再根据分类对象拿到分类名称)
            Category category = categoryService.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                //设置分类名
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

        //设置records
        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    /**
     * 根据dishId查询菜品信息和对应的口味信息
     * @param dishId
     * @return
     */
    @GetMapping("/{dishId}")
    public R<DishDto> get(@PathVariable Long dishId){
        log.info("dishId:{}",dishId);
        //根据id查询当前菜品信息，用于菜品信息回显
        DishDto dishDto = dishService.getByIdWithFlavor(dishId);
        return R.success(dishDto);
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional
    public R<String> delete(@RequestParam List<Long> ids){

        log.info("要删除的菜品id为{}",ids);

        dishService.removeWithFlavor(ids);

        return R.success("修改成功");

    }

    /**
     * 更新状态
     * @param status
     * @param ids
     * @return
     */

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("dishDto:{}",ids);

        //由ids得到dishes
        List<Dish> dishes = dishService.listByIds(ids);

        //遍历每个dish，将其status赋为传入的status
        dishes.stream().map((item) -> {//每一个item就是一个Dish实体
            //将每个dish的status设置为传入参数status
            item.setStatus(status);
            //更新每个dish
            dishService.updateById(item);
            return item;
        }).collect(Collectors.toList());

        return R.success("修改成功");
    }


    /**
     * 根据条件查询对于的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        List<DishDto> dishDtoList = null;

        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1715246935838859266_1

        //todo-优化 先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //如果存在，直接返回，无需查询数据库
        if (dishDtoList != null){
            return R.success(dishDtoList);
        }

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis

        //条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        //添加查询条件-根据id来查询
        wrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //添加查询条件-只查启售的菜品 status=1的（0的为禁售不用显示）
        wrapper.eq(Dish::getStatus,1);
        //添加排序条件-优先根据sort正序排序，sort相同时根据updatetime逆序排序（最近更新的排前面）
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询
        List<Dish> list = dishService.list(wrapper);

        dishDtoList = list.stream().map((item) -> { //item代表每个遍历出来的Dish对象
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            ////根据分类id找分类name
            //得到分类id
            Long categoryId = item.getCategoryId();
            //根据分类id得到分类name (分类id查询分类对象 再根据分类对象拿到分类名称)
            Category category = categoryService.getById(categoryId);
            if (category != null){
                String categoryName = category.getName();
                //设置分类名
                dishDto.setCategoryName(categoryName);
            }
            ////查询口味数据
            //得到当前菜品id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(dishId != null,DishFlavor::getDishId,dishId);
            //select * from dish_falvor where dish_id = ?
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(dishFlavors);

            return dishDto;
        }).collect(Collectors.toList());

        //todo-优化 如果不存在，查询数据库，将查询到的菜品数据缓存到redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);

        //返回
        return R.success(dishDtoList);
    }
}
